import { Popconfirm, Button, App, Table } from 'antd'
import type { ColumnProps } from 'antd/lib/table'
import { colors } from '@/desktop/styles'
import { saveTask, type Task, Status, statusColors } from '../logics'

export function TasksTable({
  tasks,
  reload,
  edit,
  showDetail,
}: {
  tasks: Task[]
  reload: () => Promise<void>
  edit: (task: Task) => void
  showDetail: (task: Task) => void
}) {
  const { message } = App.useApp()

  async function cancel(task: Task) {
    const actionName = task.status === Status.已完成 ? '取消' : '终止'
    const res = await saveTask({ ...task, status: Status.已取消 })
    if (res.success) void message.success('任务已' + actionName)
    else void message.success('任务' + actionName + '失败：' + res.error)

    await reload()
  }

  const columns: ColumnProps<Task>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 90,
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '任务名称',
      dataIndex: 'name',
      width: 160,
      sorter: (a, b) => a.name.localeCompare(b.name),
    },
    {
      title: '群发对象',
      dataIndex: 'targetType',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      width: 200,
      render(created: Task['created']) {
        return created.format('YYYY-MM-DD HH:mm:ss')
      },
      sorter: (a, b) => a.created.valueOf() - b.created.valueOf(),
    },
    {
      title: '开始时间',
      width: 240,
      dataIndex: 'startAt',
      render(startAt: Task['startAt'], task) {
        if (startAt !== null) return startAt.format('YYYY-MM-DD HH:mm:ss')
        else
          return <>
            立刻开始
            <span css={{ color: colors.gray, fontSize: '12px' }}>
              （{task.created.format('YYYY-MM-DD HH:mm:ss')}）
            </span>
          </>
      },
      sorter: (a, b) => (a.startAt ?? a.created).valueOf() - (b.startAt ?? b.created).valueOf(),
    },
    {
      title: '任务状态',
      width: 160,
      dataIndex: 'status',
      render(status: Status) {
        return <span css={{ color: statusColors[status] }}>{Status[status]}</span>
      },
    },
    {
      title: '操作',
      render(_: unknown, task) {
        const { status } = task
        const cancelName = status === Status.未开始 ? '取消' : '终止'

        return <div css={s.actions}>
          <Button type="link" onClick={() => showDetail(task)}>
            详情
          </Button>

          {status === Status.未开始 ? (
            <Button type="link" onClick={() => edit(task)}>
              编辑
            </Button>
          ) : null}

          {status === Status.未开始 || status === Status.发送中 ? (
            <Popconfirm
              title={'确定' + cancelName + '此任务吗？'}
              onConfirm={async () => cancel(task)}
            >
              <Button type="link">{cancelName}</Button>
            </Popconfirm>
          ) : null}
        </div>
      },
    },
  ]
  return <Table dataSource={tasks} columns={columns} rowKey="id" />
}

const s = {
  actions: css`
    button {
      margin-right: 6px;
      padding: 4px;
    }
  `,
}
